ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Template Reference Variable in Angular

This guide explains the Template Reference Variable in Angular. We find out what template reference variable is. How to define and use it in Angular.

Template Reference Variable

The Template reference variable is a reference to any DOM element,component or a directive in the Template. We can use it elsewhere in the template. We can also pass it to a method in the component. It can contain a reference to elements like h1,div, etc

Defining Template Reference variable

We declare Template reference variables using # followed by the name of the variable (#variable). We can also declare them using #variable="customer" when the component/directive defines a customer as the exportAs Property.

For Example

HTML Element
                              
 
<input type="text" #firstName>
                            
                        
Component/Directive
                              

<app-customer #customerList=”customer”></app-customer>
                            
                        
Component/Directive with exportAs
                              

<app-customer #customerList=”customer”></app-customer>
                            
                        

Template Reference variable Example

Now let us create a simple sample application to learn how to use a template reference variable

Create a new application

                              

ng new templateVariable
                            
                        

HTML Element

The following Example code defines the #firstName & #lastName template reference variables. They both contain the reference to the input HTML Element.

The input elements contain the value property. Hence we can use it to display the welcome message as shown below.

app.component.html
                              
 
<h1>{{title}}</h1>
 
<p>
 <label for="firstName">First Name</label>
 <input (keyup)="0" type="text" #firstName id="firstName">
</p>
 
<p>
 <label for="lastName">Last Name</label>
 <input (keyup)="0" type="text" #lastName id="lastName">
</p>
 
<b>Welcome {{firstName.value}} {{lastName.value}} </b>
 
                            
                        

We have used (keyup)="0" on the input element. It does nothing but it forces the angular to run the change detection. change detection, in turn, updates the view.

The Angular updates the view, when it runs the change detection. The change detection runs only in response to asynchronous events, such as the arrival of HTTP responses, raising of events, etc. In the example above whenever you type on the input box, it raises the keyup event. It forces the angular to run the change detection, hence the view gets the latest values.

Pass Variable to Component class

You can also pass the variables to the component as shown below. Add this code app.component.html

                              
 
<p>
<button (click)="sayHello(firstName, lastName)"> Say Hello</button>
</p>
 
 
                            
                        

Add this to app.component.ts

                              

sayHello(firstName, lastName) {
  alert('Hello '+firstName.value+' '+ lastName.value)
}
 
                            
                        

Component/Directive

You can get a reference to the component or directive. Refer to the tutorial on How to create child/nested component in Angular

Create a new component customer-list.component.ts

                              

import { Component } from '@angular/core';
import { Customer } from './customer';
 
@Component({
  selector: 'app-customer-list',
  templateUrl: './customer-list.component.html',
  exportAs:'customerList'
})
export class CustomerListComponent {
 
  selectedCustomer
 
  customers: Customer[] = [
 
    {customerNo: 1, name: 'Rahuld Dravid', address: '', city: 'Banglaore', state: 'Karnataka', country: 'India'},
    {customerNo: 2, name: 'Sachin Tendulkar', address: '', city: 'Mumbai', state: 'Maharastra', country: 'India'},
    {customerNo: 3, name: 'Saurrav Ganguly', address: '', city: 'Kolkata', state: 'West Bengal', country: 'India'},
    {customerNo: 4, name: 'Mahendra Singh Dhoni', address: '', city: 'Ranchi', state: 'Bihar', country: 'India'},
    {customerNo: 5, name: 'Virat Kohli', address: '', city: 'Delhi', state: 'Delhi', country: 'India'},
 
  ]
}
                            
                        
customer-list.component.html
                              
 
<h2>List of Customers</h2>
 
<table class='table'>
  <thead>
    <tr>
      <th>No</th>
      <th>Name</th>
      <th>Address</th>
      <th>City</th>
      <th>State</th>
      <th>Select</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let customer of customers;">
      <td>{{customer.customerNo}}</td>
      <td>{{customer.name}}</td>
      <td>{{customer.address}}</td>
      <td>{{customer.city}}</td>
      <td>{{customer.state}}</td>
      <button (click)="selectedCustomer=customer">Select</button>
    </tr>
  </tbody>
</table>
 
                            
                        
customer.ts
                              

export class Customer {
 
  customerNo: number;
  name:string ;
  address:string;
  city:string;
  state:string;
  country:string;
 
}
 
                            
                        
app.component.html
                              

You have selected {{customerListComponent.selectedCustomer?.name}}
<app-customer-list #customerListComponent></app-customer-list>
 
                            
                        

ExportAs

Sometimes there could be more than one directive on a DOM Element.

For Example in the following code has two directives. In such a case, we need to specify which directive to use for #variable.

                              

<a-directive b-directive #variable />
                            
                        

The components or directives can use exportAs to export the component/directive in a different name.

For Example, open the customer-list.component and add the exportAs:'customerList' under the @Component metadata

                              

@Component({
 selector: 'app-customer-list',
 templateUrl: './customer-list.component.html',
 exportAs:'customerList'
})
 
 
                            
                        

Now you can use it a

The safe navigation operator ( ? )

The selectedCustomer is null when the app starts for the first time. It gets its value only when the user clicks on the select button. Hence we use ? or a safe navigation operator to guard against null or undefined value.

Without ? the app will throw error and stops

Template Driven Forms

The ngForm directive uses the exportAs to export an instance of itself using the name ngForm. We use this in the template-driven forms in Angular.

                              

<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
                            
                        

Now, you can check value and validate the status of the form within the template

                              

<pre>Value : {{contactForm.value | json }} </pre>
<pre>Valid : {{contactForm.valid}} </pre>
<pre>Touched : {{contactForm.touched  }} </pre>
<pre>Submitted : {{contactForm.submitted  }} </pre>
 
                            
                        

Template Input Variable

The Template reference variable must not be confused with the Template input variable, which we define using the let keyword in the template.

For Example, check the ngFor loop in the customer-list.component.html. The variable customer is a template input variable

                              

 <tr *ngFor="let customer of customers;">
     <td>{{customer.customerNo}}</td>
     <td>{{customer.name}}</td>
     <td>{{customer.address}}</td>
     <td>{{customer.city}}</td>
     <td>{{customer.state}}</td>
     <button (click)="selectedCustomer=customer">Select</button>
   </tr>
 
 
                            
                        

Variable Scope

The scope of the template reference variable is the template within which it is declared. You cannot access it outside the template.

Hence any variable declared in CustomerListComponent cannot be accessed from the app component although we render the customer list within the app component.

Child scope

Also, note that we can create a new child template scope (nested scope) by using the directive ng-template. Also the structural directive like ngIf, ngFor, etc also creates their own child scope.

The following is an example of the <ng-template> directive. The address variable defined inside the ng-template is not accessible outside it.

ngIf Example

                              

<div *ngIf="true">
  <app-customer-list #variable></app-customer-list
  //variable is accessible from here
</div>
 
//variable is not accessible from here
 
 
                            
                        

summary

The Template reference variable is a reference to any DOM element, component or a directive in the Template. Use #variable to create a reference to it. We can also use #variable=”exportAsName” when the component/directive defines an exportAs metadata. The template variable can be used anywhere in the template. The variable can be passed the component as an argument to a method. The Template reference variable is different from the template input variable which we define using the let keyword within the template. They are Template scoped. Also, make use of the safe navigation operator ?, if you expect a null value.